package cn.psvmc.cxzapi.service.order;

import cn.psvmc.cxzapi.config.mybatisplus.service.impl.AbstractService;
import cn.psvmc.cxzapi.exception.ServiceException;
import cn.psvmc.cxzapi.mapper.customer.TCustomerAuthMapper;
import cn.psvmc.cxzapi.mapper.customer.TCustomerMapper;
import cn.psvmc.cxzapi.mapper.goods.TGoodsMapper;
import cn.psvmc.cxzapi.mapper.goods.TGoodsSpecsMapper;
import cn.psvmc.cxzapi.mapper.order.*;
import cn.psvmc.cxzapi.mapper.store.TStoreMapper;
import cn.psvmc.cxzapi.model.common.*;
import cn.psvmc.cxzapi.model.customer.TCustomer;
import cn.psvmc.cxzapi.model.customer.TCustomerAuth;
import cn.psvmc.cxzapi.model.goods.TGoods;
import cn.psvmc.cxzapi.model.order.*;
import cn.psvmc.cxzapi.model.system.TUser;
import cn.psvmc.cxzapi.service.alipay.AlipayCreate;
import cn.psvmc.cxzapi.service.system.ServiceUtil;
import cn.psvmc.cxzapi.util.CodeUtil;
import cn.psvmc.cxzapi.util.ToolUtils;
import com.alibaba.fastjson2.JSON;
import com.alipay.api.response.*;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.sun.istack.NotNull;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.time.*;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.concurrent.*;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;
import java.util.stream.Collectors;

/**
 * 订单表 服务实现类
 *
 * @Author auto
 * @Date 2024-08-12
 */
@Service
@Slf4j
public class TOrderService extends AbstractService<TOrderMapper, TOrder> {

    @Resource
    private TOrderMapper tOrderMapper;
    @Resource
    private TOrderContractMapper orderContractMapper;
    @Resource
    private TOrderLogService orderLogService;
    @Resource
    private ServiceUtil serviceUtil;
    @Resource
    private TOrderBillMapper tOrderBillMapper;
    @Resource
    private TPayDetailMapper payDetailMapper;
    @Resource
    private TCustomerAuthMapper customerAuthMapper;
    @Resource
    private TStoreMapper storeMapper;
    @Resource
    private TGoodsMapper goodsMapper;
    @Resource
    private TOrderCommMapper orderCommMapper;
    @Resource
    private TCustomerMapper customerMapper;
    @Resource
    private TGoodsSpecsMapper goodsSpecsMapper;
    @Resource
    private TOrderRecordMapper tOrderRecordMapper;
    //读写锁（多个线程可以同时持有读锁，但只能有一个线程持有写锁。适用于读多写少的场景）
    private final ReadWriteLock rwLock = new ReentrantReadWriteLock();
    int nThreads = Math.min(10, Runtime.getRuntime().availableProcessors());
    ExecutorService executor = Executors.newFixedThreadPool(nThreads);



    /**
     * @Description 修改押金
     * @Date 2024/9/14 22:41
     * @Author YWX
     * @Param [tOrder]
     * @Return int
     **/
    public void editDeposit(TOrder tOrder) {
        TOrder originTOrder = checkOrder(tOrder.getOrderId());//校验订单是否存在
        // 比较数据版本号
        if (!originTOrder.getRversion().equals(tOrder.getRversion())) {
            throw new ServiceException("数据已更新，请刷新后重试！");
        } else if (originTOrder.getConfirmed().equals(1)) {
            throw new ServiceException("订单已确认，无法修改押金！");
        }

        // 字段为null 不更新
        TOrder updateTOrder = new TOrder();
        updateTOrder.setOrderId(tOrder.getOrderId());
        updateTOrder.setDeposit(tOrder.getDeposit());
        updateTOrder.setRversion(tOrder.getRversion());
        tOrderMapper.updateById(updateTOrder);
        TOrderLog orderLog = new TOrderLog();
        orderLog.setOrderCode(originTOrder.getOrderCode());
        orderLog.setLogType("修改押金");
        orderLog.setComm("押金由：" + originTOrder.getDeposit() + "，修改为：" + tOrder.getDeposit());
        orderLogService.saveOrderLog(orderLog);
    }

    //校验订单是否存在
    private TOrder checkOrder(Integer orderId) {
        // 通过id查询数据处理 详情
        TOrder originTOrder = tOrderMapper.selectById(orderId);
        if (originTOrder == null) {
            throw new ServiceException("未查询到对应的订单表信息！");
        }
        return originTOrder;
    }

    //校验订单是否存在
    private TOrder checkOrderByIdOrCode(Integer orderId, String orderCode) {
        // 通过id查询数据处理 详情
        TOrder originTOrder;
        if (ToolUtils.isTrueInteger(orderId)) {
            originTOrder = tOrderMapper.selectById(orderId);//根据订单id获取订单信息
        } else {
            originTOrder = tOrderMapper.selectByOrderCode(orderCode);//根据订单id获取订单信息
        }
        if (originTOrder == null) {
            throw new ServiceException("未查询到对应的订单表信息！");
        }
        return originTOrder;
    }

    /**
     * @Date auto 2024-08-12 查询订单表详情
     * @Param id 唯一id
     * @Return cn.psvmc.cxzapi.model.order.TOrder
     */
    public Map<String, Object> detail(Integer id) {
        return tOrderMapper.findById(id);
    }

    /**
     * @Description 订单列表
     * @Date 2024/8/26 17:15
     * @Author YWX
     * @Param [iPage, entity]
     * @Return com.baomidou.mybatisplus.core.metadata.IPage<java.util.Map < java.lang.String, java.lang.Object>>
     **/
    public IPage<Map<String, Object>> list(Page<TOrder> iPage, OrderEntity entity) {
        IPage<Map<String, Object>> list = tOrderMapper.listAll(iPage, entity);
        List<Map<String, Object>> records = list.getRecords();
        if (ToolUtils.isListEmpty(records)) {
            return list;
        }
        List<Integer> orderIds = records.stream().map(item -> ToolUtils.objToInteger(item.get("orderId"))).distinct().collect(Collectors.toList());
        Map<Integer, List<TOrderBill>> billsMap = tOrderBillMapper.listCustomerBillsByOrderIds(orderIds).stream().collect(Collectors.groupingBy(TOrderBill::getOrderId));
        records.forEach(item -> {
            List<TOrderBill> bills = billsMap.get(ToolUtils.objToInteger(item.get("orderId")));
            Map<String, Object> depositRentNum = (Map<String, Object>) item.get("depositRentNum");
            if (ToolUtils.isListNotEmpty(bills)) {
                TOrderBill bill1 = bills.get(0);
                depositRentNum.put("rentFirst", bill1.getPayAmount());
                depositRentNum.put("rentEnd", bills.get(bills.size() - 1).getPayAmount());
                double periodLeft = 0;
                if (bills.size() > 1) {
                    TOrderBill bill2 = bills.get(1);
                    periodLeft = bill2.getPayAmount();
                }
                depositRentNum.put("periodLeft", periodLeft);
                double depositPay = ToolUtils.formatDouble2(bills.stream().filter(ob -> ToolUtils.payStatus.contains(ob.getBillStatus())).mapToDouble(TOrderBill::getDepositPay).sum());
                depositRentNum.put("depositPay", depositPay);
                Map<String, Object> payInfo = (Map<String, Object>) item.get("payInfo");
                double realPayAmount = ToolUtils.formatDouble2(bills.stream().filter(ob -> ToolUtils.payStatus.contains(ob.getBillStatus())).mapToDouble(TOrderBill::getPayAmount).sum());
                payInfo.put("realPayAmount", realPayAmount);//实付总租金
                LocalDateTime lastPayTime = bills.stream().filter(ob -> ToolUtils.payStatus.contains(ob.getBillStatus())).map(TOrderBill::getPayTime).max(LocalDateTime::compareTo).orElse(null);
                payInfo.put("lastPayTime", lastPayTime);
                double realStoreAmount = ToolUtils.formatDouble2(bills.stream().filter(ob -> ToolUtils.payStatus.contains(ob.getBillStatus())).mapToDouble(TOrderBill::getStoreAmount).sum());
                payInfo.put("realStoreAmount", realStoreAmount);
                double realBillAmount = ToolUtils.formatDouble2(bills.stream().filter(ob -> ToolUtils.payStatus.contains(ob.getBillStatus())).mapToDouble(TOrderBill::getBillAmount).sum());
                payInfo.put("realBillAmount", realBillAmount);//应付总租金
                double payAmount = ToolUtils.formatDouble2(bills.stream().mapToDouble(TOrderBill::getPayAmount).sum());
                payInfo.put("feesTotalAmount", ToolUtils.add(payAmount, ToolUtils.objToDouble(payInfo.get("shippingFee"))));
                double billAmount = ToolUtils.formatDouble2(bills.stream().mapToDouble(TOrderBill::getBillAmount).sum());
                payInfo.put("feesTotalRent", billAmount);
                payInfo.put("couponAmount", ToolUtils.subtract(billAmount, payAmount));
                payInfo.put("realTotalPayAmount", payAmount);
                double refundAmount = 0.0;
                for (TOrderBill ob : bills) {
                    if (ToolUtils.refundStatus.contains(ob.getBillStatus())) {
                        refundAmount = ToolUtils.add(refundAmount, ToolUtils.subtract(ob.getPayAmount(), ob.getAvailableAmount()));
                    }
                }
                double availableAmount = ToolUtils.formatDouble2(bills.stream().filter(ob -> ToolUtils.payStatus.contains(ob.getBillStatus())).mapToDouble(TOrderBill::getAvailableAmount).sum());
                payInfo.put("availableAmount", availableAmount);//可用金额
                payInfo.put("refundAmount", refundAmount);//已退款金额
            }

            item.put("log", orderLogService.getLastLogByOrderCode(item.get("orderCode")));
        });
        return list;
    }

    /**
     * @Description 添加订单协议
     * @Date 2024/8/24 10:11
     * @Author YWX
     * @Param [contract]
     * @Return void
     **/
    public void addContract(TOrderContract contract) {
        orderContractMapper.insert(contract);
        TOrderLog log = new TOrderLog();
        log.setOrderCode(tOrderMapper.getCodeById(contract.getOrderId()));
        log.setLogType("补充协议");
        log.setComm("协议地址：" + contract.getPath());
        orderLogService.saveOrderLog(log);
    }

    /**
     * @Description 订单分配
     * @Date 2024/8/24 10:25
     * @Author YWX
     * @Param [order]
     * @Return void
     **/
    public void setManager(TOrder order) {
        TOrder tOrder = checkOrder(order.getOrderId());//校验订单是否存在
        tOrderMapper.setManager(order.getOrderId(), order.getManagerId());
        TOrderLog log = new TOrderLog();
        log.setOrderCode(tOrder.getOrderCode());
        log.setLogType("订单分配");
        log.setComm("分配给：" + serviceUtil.getUserNameById(order.getManagerId()));
        orderLogService.saveOrderLog(log);
    }

    /**
     * @Description 订单协议列表
     * @Date 2024/8/24 16:00
     * @Author YWX
     * @Param [orderId]
     * @Return java.util.List<java.util.Map < java.lang.String, java.lang.Object>>
     **/
    public List<Map<String, Object>> listContract(Integer orderId) {
        return orderContractMapper.listContract(orderId);
    }

    /**
     * @Description 补订单
     * @Date 2024/8/26 8:54
     * @Author YWX
     * @Param [order]
     * @Return void
     **/
    @Transactional(rollbackFor = Exception.class)
    public void supplementOrder(OrderOperate oo) {
        Integer orderId = oo.getOrderId();
        TOrder tOrder = checkOrder(orderId);
        if (tOrder.getOrderStatus().equals(7)) {
            throw new ServiceException("订单已取消，禁止操作！");
        }
        TOrder order = new TOrder();
        order.setOrderType(oo.getOrderType());
        order.setRent(oo.getRent());
        order.setRentAfterCoupon(oo.getRent());
        order.setPlanBegin(ToolUtils.getBeginDateTime(oo.getPlanBegin()));
        order.setPlanEnd(ToolUtils.getEndDateTime(oo.getPlanEnd()));
        order.setRealBegin(order.getPlanBegin());
        order.setRealEnd(order.getPlanEnd());
        order.setStoreid(tOrder.getStoreid());
        order.setUsername(tOrder.getUsername());
        order.setUserphone(tOrder.getUserphone());
        order.setUserAddress(tOrder.getUserAddress());
        order.setOrderPid(orderId);
        order.setLeasePeriod(1);
        order.setDay(ToolUtils.getDaysBetween(order.getPlanBegin(), order.getPlanEnd()));
        order.setGoodsId(tOrder.getGoodsId());
        order.setGsid(tOrder.getGsid());
        order.setOrderCode(CodeUtil.generateOrderCode());
        order.setCustomerid(tOrder.getCustomerid());
        order.setControlReport(tOrder.getControlReport());
        order.setReportContent(tOrder.getReportContent());
        order.setVerifyRecomment(tOrder.getVerifyRecomment());
        order.setScoreNormExplain(tOrder.getScoreNormExplain());
        order.setSettlementRatio(tOrder.getSettlementRatio());
        order.setRenewalRate(tOrder.getRenewalRate());
        order.setDepositStatus(1);
        order.setOrderStatus(4);
        tOrderMapper.insert(order);

        TOrderBill bill = new TOrderBill();
        bill.setTransactionId(CodeUtil.generateBillSequence());
        bill.setOrderId(order.getOrderId());
        bill.setPeriod(1);
        bill.setOldPeriod(1);
        bill.setBillAmount(order.getRent());
        bill.setOldAmount(bill.getBillAmount());
        bill.setBillStatus(0);
        bill.setBeginTime(order.getPlanBegin());
        bill.setEndTime(order.getPlanEnd());
        bill.setPlanDate(oo.getPlanBegin());
        bill.setPayAmount(order.getRent());
        serviceUtil.setStoreAmount(bill);
        bill.setStoreid(tOrder.getStoreid());
        bill.setStageNo(1L);
        bill.setInstallmentNo(bill.getPeriod());
        tOrderBillMapper.insert(bill);

        String comm = serviceUtil.getUserName() + "添加了补单-";
        Integer orderType = order.getOrderType();
        if (orderType.equals(2)) {
            comm += "买断订单";
        } else if (orderType.equals(3)) {
            comm += "赔偿款";
        } else if (orderType.equals(4)) {
            comm += "运费";
        } else if (orderType.equals(5)) {
            comm += "补租金";
        } else if (orderType.equals(6)) {
            comm += "补押金";
        }
        comm += ",金额" + order.getRent() + "元";
        String ooComm = oo.getComm();
        if (ToolUtils.isNotEmpty(ooComm)) {
            comm += ",备注：" + ooComm;
        }

        TOrderLog log = new TOrderLog();
        log.setOrderCode(tOrder.getOrderCode());
        log.setLogType("补单");
        log.setComm(comm);
        orderLogService.saveOrderLog(log);
    }

    /**
     * @Description 账单退款
     * @Date 2024/10/30 22:31
     * @Author YWX
     * @Param [obid]
     * @Return void
     **/
    public void billRefund(Integer obid) {
        TOrderBill bill = tOrderBillMapper.selectById(obid);
        if (bill.getBillStatus().equals(0)) {
            throw new ServiceException("账单未支付，无法退款！");
        } else if (bill.getBillStatus().equals(2)) {
            throw new ServiceException("账单已退款，请勿重复操作！");
        } else if (bill.getBillStatus().equals(22)) {
            throw new ServiceException("账单已部分退款，请勿重复操作！");
        } else if (bill.getBillStatus().equals(3)) {
            throw new ServiceException("账单已关闭，无法退款！");
        }
        TOrderLog log = new TOrderLog();
        try {
            serviceUtil.orderBillRefund(bill, 34);
            log.setOrderCode(tOrderMapper.getCodeById(bill.getOrderId()));
            log.setLogType("账单退款");
            log.setComm("退款金额：" + bill.getAvailableAmount() + "元");
        } catch (Exception e) {
            log.setComm("账单退款失败：" + e.getMessage());
        }
        orderLogService.saveOrderLog(log);
    }

    /**
     * @Description 修改账单金额
     * @Date 2024/8/26 10:03
     * @Author YWX
     * @Param [bill]
     * @Return void
     **/
    @Transactional(rollbackFor = Exception.class)
    public void updateBillAmount(TOrderBill bill) {
        TOrderBill orderBill = checkOrderBill(bill);//校验账单信息
        if (orderBill.getIsGenerate().equals(1)) {
            throw new ServiceException("此账单已生成，无法修改金额！");
        } else if (!orderBill.getBillStatus().equals(0)) {
            throw new ServiceException("非待支付账单，无法修改金额！");
        }

        //修改账单金额
        bill.setOrderId(orderBill.getOrderId());
        bill.setPayAmount(bill.getBillAmount());
        serviceUtil.setStoreAmount(bill);
        bill.setObid(orderBill.getObid());
        tOrderBillMapper.updateById(bill);

        TOrder updateOrder = new TOrder();
        updateOrder.setOrderId(orderBill.getOrderId());
        if (orderBill.getOrderType().equals(1)) {
            double subtract = ToolUtils.subtract(orderBill.getPayAmount(), bill.getPayAmount());
            updateOrder.setRent(ToolUtils.subtract(orderBill.getRent(), subtract));
            updateOrder.setRentAfterCoupon(ToolUtils.subtract(orderBill.getRentAfterCoupon(), subtract));
        } else {//补订单
            updateOrder.setRent(bill.getBillAmount());
            updateOrder.setRentAfterCoupon(bill.getBillAmount());
        }
        tOrderMapper.updateById(updateOrder);

        //添加操作日志
        TOrderLog log = new TOrderLog();
        log.setOrderCode(orderBill.getOrderCode());
        String userName = serviceUtil.getUserName();
        String logComm = userName + "修改第" + bill.getPeriod() + "期账单金额为：" + bill.getBillAmount() + "元";
        String comm = bill.getComm();
        if (ToolUtils.isNotEmpty(comm)) {
            logComm += ";备注：" + comm;
        }
        log.setComm(logComm);
        log.setLogType("修改账单金额");
        log.setFilePath(bill.getFilePath());

        serviceUtil.orderModify(orderBill.getOrderId(), orderBill.getOrderCode(), orderBill.getCustomerid(), log);
    }

    /**
     * @Description 操作日志
     * @Date 2024/8/26 10:24
     * @Author YWX
     * @Param [iPage, entity]
     * @Return com.baomidou.mybatisplus.core.metadata.IPage<java.util.Map < java.lang.String, java.lang.Object>>
     **/
    public IPage<Map<String, Object>> listLog(Page<TOrderLog> iPage, OrderEntity entity) {
        return orderLogService.listAll(iPage, entity);
    }

    /**
     * @Description 修改账单支付状态
     * @Date 2024/8/26 11:08
     * @Author YWX
     * @Param [bill]
     * @Return void
     **/
    @Transactional(rollbackFor = Exception.class)
    public void updateBillStatus(TOrderBill bill) {
        Integer billStatus = bill.getBillStatus();
        if (!billStatus.equals(0) && !billStatus.equals(1)) {
            throw new ServiceException("账单状态不正确！");
        }
        TOrderBill orderBill = checkOrderBill(bill);//校验账单信息

        Integer oldBillStatus = orderBill.getBillStatus();
        if (billStatus.equals(oldBillStatus)) {
            return;
        }
        if (oldBillStatus.equals(22)) {
            throw new ServiceException("账单已部分退款，请勿重复操作！");
        }
        bill.setObid(orderBill.getObid());
        int firstPayStatus;
        String status;
        if (billStatus.equals(1)) {//改为已支付
            firstPayStatus = 1;
            status = "已支付";
            LocalDateTime now = LocalDateTime.now();
            String nowTime = now.format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
            bill.setRealDate(nowTime);
            bill.setCutTime(now);
            bill.setPayTime(now);
            /*if (oldBillStatus.equals(0)) {
                serviceUtil.addAccountBillByTradeNo(bill.getTransactionId(), 1, 31);//支付租金
            }*/
        } else {//改为未支付
            firstPayStatus = 0;
            status = "未支付";
            bill.setRealDate("");
            AlipayTradeQueryResponse response = AlipayCreate.alipayTradeQuery(bill.getTransactionId(), bill.getTradeNo());
            if ("交易不存在".equals(response.getSubMsg())) {
                billStatus = 0;
            } else {
                billStatus = 2;
            }

            bill.setBillStatus(billStatus);
            /*if (oldBillStatus.equals(1)) {
                serviceUtil.addAccountBillByTradeNo(bill.getTransactionId(), 2, 34);//账单退款
            }*/
        }
        bill.setTradeStatus(billStatus);
        tOrderBillMapper.updateById(bill);

        if (orderBill.getPeriod().equals(1)) {
            tOrderMapper.updateFirstPayStatusById(orderBill.getOrderId(), firstPayStatus);//修改订单首次支付状态
        }


        //添加操作日志
        TOrderLog log = new TOrderLog();
        log.setOrderCode(orderBill.getOrderCode());
        String userName = serviceUtil.getUserName();
        log.setComm(userName + bill.getComm());
        log.setLogType("修改账单支付状态");
        log.setFilePath(bill.getFilePath());
        orderLogService.saveOrderLog(log);
    }

    //校验账单信息
    private TOrderBill checkOrderBill(TOrderBill bill) {
        TOrderBill orderBill = tOrderBillMapper.selectByOrderIdAndPeriod(bill.getOrderId(), bill.getPeriod(), bill.getOrderCode());//根据订单编号获取订单信息
        if (orderBill == null) {
            throw new ServiceException("未查询到账单信息！");
        }
        return orderBill;
    }

    /**
     * @Description 账单列表
     * @Date 2024/8/26 11:35
     * @Author YWX
     * @Param [queryPage, entity]
     * @Return com.baomidou.mybatisplus.core.metadata.IPage<java.util.Map < java.lang.String, java.lang.Object>>
     **/
    public IPage<Map<String, Object>> listBill(Page<TOrderLog> queryPage, OrderEntity entity) {
        if (ToolUtils.isEmpty(entity.getOrderCode())) {
            setStoreId(entity);
        }
        return tOrderBillMapper.listBill(queryPage, entity);
    }

    /**
     * @Description 账单导出列表
     * @Date 2024/8/26 11:39
     * @Author YWX
     * @Param [entity]
     * @Return java.util.List<java.util.Map < java.lang.String, java.lang.Object>>
     **/
    public List<Map<String, Object>> listExportBill(OrderEntity entity) {
        setStoreId(entity);
        return tOrderBillMapper.listBill(entity);
    }

    /**
     * @Description 冻结押金转支付
     * @Date 2024/8/26 16:55
     * @Author YWX
     * @Param [order]
     * @Return void
     **/
    @Transactional(rollbackFor = Exception.class)
    public void convertDepositToPayment(TOrder order) {
        TOrder tOrder = checkOrderByIdOrCode(order.getOrderId(), order.getOrderCode());
        if (tOrder.getConfirmed().equals(0)) {
            throw new ServiceException("订单风控审核后才能发起代扣！");
        }
        Integer orderId = tOrder.getOrderId();
        Double deposit = tOrder.getRestAmount();
        if (deposit.compareTo(0.0) <= 0) {
            throw new ServiceException("此订单没有可转支付押金！");
        }

        List<TOrderBill> bills = tOrderBillMapper.getDepositPay(orderId);//获取待支付金额
        if (ToolUtils.isListEmpty(bills)) {
            return;
        }
        Double payAmount = 0.0;
        if (bills.get(0).getPayAmount().compareTo(deposit) > 0) {//如果待支付金额大于押金
            throw new ServiceException("待支付金额大于押金！");
        }
        String orderCode = tOrder.getOrderCode();
        Integer firstPayStatus = null;
        //发起分期单
        String openid = customerMapper.getOpenIdByCustomerId(tOrder.getCustomerid());
        String type = ToolUtils.getTypeByOrderType(tOrder.getOrderType());
        String body = "商家：" + serviceUtil.getStoreName(tOrder.getStoreid()) + "；订单号：" + tOrder.getOrderCode();
        for (int i = 0; i < bills.size(); i++) {
            TOrderBill bill = bills.get(i);
            Double amount = bill.getPayAmount();
            if (i == 0) {
                if (amount.compareTo(deposit) > 0) {//如果待支付金额大于押金
                    throw new ServiceException("待支付金额大于押金！");
                }
                payAmount = amount;
            } else {
                payAmount = ToolUtils.add(payAmount, amount);
                if (payAmount.compareTo(deposit) > 0) {
                    break;
                }
            }
            bill.setOrderCode(orderCode);
            String installmentOrderId = null;
            if (tOrder.getConfirmed().equals(1)) {
                AlipayOpenMiniOrderInstallmentCreateResponse createResponse = AlipayCreate.orderInstallmentCreate(bill, openid, type, false);
                installmentOrderId = createResponse.getInstallmentOrderId();
            }
            updateBillStatus(bill.getObid(), bill.getTransactionId(), tOrder.getAuthNo(), amount, orderId, installmentOrderId, tOrder.getTradeComponentOrderId(), body);//更新账单状态

            if (bill.getPeriod().equals(1)) {
                firstPayStatus = 1;
            }
        }

        updateRestAmountByCode(orderCode, tOrder.getRestAmount(), firstPayStatus);//更新订单剩余冻结金额

        //添加操作日志
        TOrderLog log = new TOrderLog();
        log.setOrderCode(tOrder.getOrderCode());
        String userName = serviceUtil.getUserName();
        log.setComm(userName + "冻结押金转支付,支付金额：" + payAmount + "元");
        log.setLogType("冻结押金转支付");
        orderLogService.saveOrderLog(log);
    }

    /**
     * @Description 修改租期
     * @Date 2024/8/26 15:19
     * @Author YWX
     * @Param [bill]
     * @Return void
     **/
    @Transactional(rollbackFor = Exception.class)
    public void updatePeriod(TOrderBill bill) {
        Integer period = bill.getPeriod();
        Integer newPeriod = bill.getNewPeriod();

        String orderCode = bill.getOrderCode();
        TOrderBill bill1 = tOrderBillMapper.selectByOrderIdAndPeriod(bill.getOrderId(), period, orderCode);
        TOrderBill bill2 = tOrderBillMapper.selectByOrderIdAndPeriod(bill.getOrderId(), newPeriod, orderCode);

        TOrderBill update1 = new TOrderBill();
        BeanUtils.copyProperties(bill1, update1);
        update1.setPeriod(bill2.getPeriod());
        update1.setBeginTime(bill2.getBeginTime());
        update1.setEndTime(bill2.getEndTime());
        update1.setPlanDate(bill2.getPlanDate());
        update1.setStageNo(bill2.getStageNo());
        update1.setInstallmentNo(bill2.getInstallmentNo());

        TOrderBill update2 = new TOrderBill();
        BeanUtils.copyProperties(bill2, update2);
        update2.setPeriod(bill1.getPeriod());
        update2.setBeginTime(bill1.getBeginTime());
        update2.setEndTime(bill1.getEndTime());
        update2.setPlanDate(bill1.getPlanDate());
        update2.setStageNo(bill1.getStageNo());
        update2.setInstallmentNo(bill1.getInstallmentNo());

        tOrderBillMapper.updateById(update1);
        tOrderBillMapper.updateById(update2);

        //添加操作日志
        TOrderLog log = new TOrderLog();
        log.setOrderCode(bill1.getOrderCode());
        String userName = serviceUtil.getUserName();
        log.setComm(userName + bill.getComm());
        log.setLogType("修改租期");
        log.setFilePath(bill.getFilePath());
        orderLogService.saveOrderLog(log);
    }

    /**
     * @Description 逾期订单列表
     * @Date 2024/8/26 22:54
     * @Author YWX
     * @Param [queryPage, entity]
     * @Return com.baomidou.mybatisplus.core.metadata.IPage<java.util.Map < java.lang.String, java.lang.Object>>
     **/
    public IPage<Map<String, Object>> listExpected(Page<TOrder> queryPage, OrderEntity entity) {
        setStoreId(entity);
        return tOrderMapper.listExpected(queryPage, entity);
    }

    /**
     * @Description 标记逾期订单
     * @Date 2024/8/26 22:59
     * @Author YWX
     * @Param [tOrder]
     * @Return void
     **/
    public void editTags(TOrder tOrder) {
        TOrder order = checkOrder(tOrder.getOrderId());
        tOrderMapper.updateById(tOrder);
        TOrderLog log = new TOrderLog();
        log.setOrderCode(order.getOrderCode());
        log.setLogType("标记逾期订单");
        log.setComm(tOrder.getTags());
        orderLogService.saveOrderLog(log);
    }

    /**
     * @Description 买断订单列表
     * @Date 2024/8/27 9:41
     * @Author YWX
     * @Param [queryPage, entity]
     * @Return com.baomidou.mybatisplus.core.metadata.IPage<java.util.Map < java.lang.String, java.lang.Object>>
     **/
    public IPage<Map<String, Object>> listBuyout(Page<TOrder> queryPage, OrderEntity entity) {
        return tOrderMapper.listBuyout(queryPage, entity);
    }

    //设置商家id
    public void setStoreId(OrderEntity entity) {
        Integer storeId = serviceUtil.getStoreId();
        if (!ToolUtils.isTrueInteger(storeId)) {
            throw new ServiceException("商家id不能为空！");
        }
        entity.setStoreid(storeId);
    }

    public void setStoreId2(OrderEntity entity) {
        TUser user = serviceUtil.getUser();
        Integer storeId = user.getStoreid();
        if (user.getUsertype().equals(2) && !ToolUtils.isTrueInteger(storeId)) {
            throw new ServiceException("商家id不能为空！");
        }
        entity.setStoreid(storeId);
    }


    /**
     * @Description 审核买断订单
     * @Date 2024/8/27 15:10
     * @Author YWX
     * @Param [order]
     * @Return void
     **/
    @Transactional(rollbackFor = Exception.class)
    public void checkBuyout(TOrder order) {
        TOrder tOrder = checkOrder(order.getOrderId());
        if (order.getCheckStatus().equals(1)) {//审核通过生成账单
            List<TOrderBill> bills = tOrderBillMapper.listCustomerBillByOrderId(tOrder.getOrderPid());
            for (TOrderBill bill : bills) {
                String tradeNo = bill.getTradeNo();
                if (bill.getBillStatus().equals(0)) {
                    serviceUtil.closeBill(bill.getObid(), bill.getTransactionId());
                }
            }
            double buyPriceAfterStore = tOrder.getBuyPriceAfterStore();
            TOrderBill bill = tOrderBillMapper.findBuyoutBillByOrderId(tOrder.getOrderId());
            if (bill != null && bill.getBillStatus().equals(0)) {
                buyPriceAfterStore = serviceUtil.getBuyPriceAfterStore(bills, tOrder.getBuyPrice());
                bill.setBillAmount(buyPriceAfterStore);
                bill.setOldAmount(bill.getBillAmount());
                bill.setPayAmount(buyPriceAfterStore);
                serviceUtil.setStoreAmount(bill);
                LocalDateTime beginTime = LocalDate.now().plusDays(1).atTime(00, 00, 00);
                bill.setBeginTime(beginTime);
                bill.setEndTime(beginTime.plusDays(3).minusSeconds(1));
                bill.setPlanDate(beginTime.minusDays(1).format(DateTimeFormatter.ofPattern("yyyy-MM-dd")));
                tOrderBillMapper.updateById(bill);
            }
            order.setBuyPriceAfterStore(buyPriceAfterStore);//实际支付买断价=买断价-商家收到的钱（扣除平台收的钱）
            order.setBuyoutStatus(2);

            TOrder parentOrder = new TOrder();
            parentOrder.setOrderId(tOrder.getOrderPid());
            parentOrder.setBuyoutStatus(2);
            parentOrder.setBuyPriceAfterStore(buyPriceAfterStore);
            tOrderMapper.updateById(parentOrder);
            order.setRent(buyPriceAfterStore);
            order.setRentAfterCoupon(buyPriceAfterStore);
            order.setPlanBegin(bill.getBeginTime());
            order.setPlanEnd(bill.getEndTime());
            order.setRealBegin(bill.getBeginTime());
            order.setRealEnd(bill.getEndTime());
            order.setDay(3);
            order.setConfirmed(1);
        } else {
            order.setBuyoutStatus(3);
        }
        order.setCheckId(serviceUtil.getUserId());
        order.setCheckTime(LocalDateTime.now());
        tOrderMapper.updateById(order);
        TOrderLog log = new TOrderLog();
        log.setOrderCode(tOrder.getOrderCode());
        log.setLogType("审核买断订单");
        String result;
        if (order.getCheckStatus().equals(1)) {
            result = "通过";
        } else {
            result = "拒绝";
        }
        String comm = "审核结果：" + result;
        String checkComm = order.getCheckComm();
        if (ToolUtils.isNotEmpty(checkComm)) {
            comm += "，审核意见：" + checkComm;
        }
        log.setComm(comm);
        orderLogService.saveOrderLog(log);
    }

    /**
     * @Description 订单付款详情
     * @Date 2024/8/27 21:17
     * @Author YWX
     * @Param [orderId]
     * @Return java.util.List<java.util.Map < java.lang.String, java.lang.Object>>
     **/
    public List<Map<String, Object>> detailPay(Integer orderId) {
        return payDetailMapper.listByOrderId(orderId);
    }

    /**
     * @Description 取消订单
     * @Date 2024/9/5 0:32
     * @Author YWX
     * @Param [orderId]
     * @Return void
     **/
    public void cancelOrder(Integer orderId) {
        Integer userId = serviceUtil.getUserId();
        String userName = "商家";
        serviceUtil.orderCancel(orderId, userId, userName, 0);
    }

    /**
     * @Description 获取客户认证信息
     * @Date 2024/9/9 23:23
     * @Author YWX
     * @Param [customerid]
     * @Return java.util.Map<java.lang.String, java.lang.Object>
     **/
    public Map<String, Object> detailAuth(Integer customerid) {
        return customerAuthMapper.findByCustomerId(customerid);
    }

    /**
     * @Description 首页-订单统计
     * @Date 2024/9/13 12:21
     * @Author YWX
     * @Param []
     * @Return java.util.Map<java.lang.String, java.lang.Object>
     **/
    public Map<String, Object> getAnalyze() {
        LocalDateTime now = LocalDateTime.now();
        return tOrderMapper.getAnalyze(serviceUtil.getStoreId(), now);
    }

    /**
     * @Description 首页-续租率
     * @Date 2024/9/13 12:25
     * @Author YWX
     * @Param [entity]
     * @Return java.lang.Double
     **/
    public Double getRenewRate(OrderEntity entity) {
        setStoreId(entity);
        if (entity.getType().equals(1)) {
            entity.setBegindate(ToolUtils.getNowDateFormat("yyyy-MM"));
        }
        return tOrderMapper.getRenewRate(entity);
    }

    /**
     * @Description 首页-收益走势
     * @Date 2024/9/17 23:21
     * @Author YWX
     * @Param [entity]
     * @Return java.lang.Double
     **/
    public List<Map<String, Object>> getEarningsTrend(OrderEntity entity) {
        setStoreId(entity);
        return tOrderMapper.getEarningsTrend(entity);
    }

    /**
     * @Description 首页-订单走势
     * @Date 2024/9/18 23:42
     * @Author YWX
     * @Param [entity]
     * @Return java.util.List<java.util.Map < java.lang.String, java.lang.Object>>
     **/
    public List<Map<String, Object>> getOrderTrend(OrderEntity entity) {
        setStoreId(entity);
        return tOrderMapper.getOrderTrend(entity);
    }

    /**
     * @Description 审核风控
     * @Date 2024/9/24 21:33
     * @Author YWX
     * @Param [tOrder]
     * @Return void
     **/
    @Transactional(rollbackFor = Exception.class)
    public void checkControl(TOrder tOrder) {
        TOrder order = checkOrder(tOrder.getOrderId());
        if (order.getControlStatus().equals(1)) {
            throw new ServiceException("订单已风控，请勿重复操作！");
        }

        Integer userId = serviceUtil.getUserId();
        int cancelCheckStatus;
        String result;
        if (tOrder.getControlStatus().equals(2)) {//拒绝
            result = "拒绝";
            cancelCheckStatus = 3;
            serviceUtil.aliOrderCancle(order);//支付宝订单取消
            tOrder.setOrderStatus(7);
            //恢复库存
            goodsSpecsMapper.recoverStock(order.getGsid(), order.getNum());
        } else {
            result = "通过";
            cancelCheckStatus = 2;
            tOrder.setConfirmed(1);
            tOrder.setConfirmedId(userId);
            tOrder.setOrderStatus(2);
            String openId = serviceUtil.getOpenIdByCustomerId(order.getCustomerid());
            AlipayCreate.alipayOpenMiniOrderDeliveryModify(order.getOrderCode(), openId, "MERCHANT_CONFIRMED");
        }
        //更新订单
        if (order.getCancelStatus().equals(1)) {
            tOrder.setCancelCheckStatus(cancelCheckStatus);
            tOrder.setCancelStatus(0);
            tOrder.setCancelCheckTime(LocalDateTime.now());
            tOrder.setCancelCheckId(userId);
        }
        tOrder.setControlId(userId);
        tOrder.setControlTime(LocalDateTime.now());
        tOrderMapper.updateById(tOrder);

        //添加操作日志
        TOrderLog log = new TOrderLog();
        log.setOrderCode(order.getOrderCode());
        log.setLogType("审核风控");
        String controlComm = tOrder.getControlComm();
        if (ToolUtils.isEmpty(controlComm)) {
            controlComm = "无";
        }
        String comm = "商家风控审核：" + result + "，审核意见：" + controlComm;
        log.setComm(comm);
        orderLogService.saveOrderLog(log);
    }

    /**
     * @Description 删除订单协议
     * @Date 2024/9/15 20:38
     * @Author YWX
     * @Param [ocid]
     * @Return void
     **/
    public void deleteContract(Integer ocid) {
        TOrderContract contract = orderContractMapper.selectById(ocid);
        orderContractMapper.deleteById(ocid);
        TOrderLog log = new TOrderLog();
        log.setOrderCode(tOrderMapper.getCodeById(contract.getOrderId()));
        log.setLogType("删除协议");
        log.setComm("协议地址：" + contract.getPath());
        orderLogService.saveOrderLog(log);
    }

    /**
     * @Description 获取风控报告
     * @Date 2024/9/17 17:25
     * @Author YWX
     * @Param [orderId]
     * @Return java.lang.String
     **/
    public String getControlReport(Integer orderId) {
        String controlReport = tOrderMapper.getControlReport(orderId);
        if (ToolUtils.isEmpty(controlReport)) {
            TCustomer tCustomer = customerMapper.getAuthByCustomerId(tOrderMapper.getCustomerIdByOrderId(orderId));
            String idNumber = tCustomer.getIdNumber();
            String reportContent;
            if (ToolUtils.isNotEmpty(idNumber)) {//如果客户已认证，且时间不超过7天，则不重新生成风控报告
                if (tCustomer.getControlReport().equals(1) && tCustomer.getDay() <= 7) {
                    reportContent = tCustomer.getReportContent();
                } else {
                    reportContent = serviceUtil.getReportContent(tCustomer.getRealName(), idNumber, tCustomer.getPhone());
                    if (ToolUtils.isNotEmpty(reportContent)) {
                        tCustomer.setReportContent(reportContent);
                        tCustomer.setControlReport(1);
                        tCustomer.setReportTime(LocalDateTime.now());
                        customerMapper.updateById(tCustomer);
                    }
                }
                TOrder tOrder = new TOrder();
                tOrder.setOrderId(orderId);
                tOrder.setReportContent(reportContent);
                tOrder.setControlReport(1);
                Map<String, Object> result = JSON.parseObject(reportContent, Map.class);
                Map<String, Object> resp_data = JSON.parseObject(ToolUtils.objToString(result.get("resp_data")), Map.class);
                tOrder.setVerifyRecomment(ToolUtils.objToString(resp_data.get("verify_recomment")));
                tOrder.setScoreNormExplain(ToolUtils.objToString(resp_data.get("score_norm_explain")));
                tOrderMapper.updateById(tOrder);
                controlReport = reportContent;
            }
        }
        return controlReport;
    }

    /**
     * @Description 订单导出列表
     * @Date 2024/9/22 21:55
     * @Author YWX
     * @Param [entity]
     * @Return java.util.List<java.util.Map < java.lang.String, java.lang.Object>>
     **/
    public List<Map<String, Object>> listExport(OrderEntity entity) {
        List<Map<String, Object>> list = tOrderMapper.listExport(entity);

        List<CompletableFuture<Void>> futures = new ArrayList<>();
        int batchSize = 100; // 每批次处理的数据量
        for (int i = 0; i < list.size(); i += batchSize) {
            int end = Math.min(i + batchSize, list.size());
            List<Map<String, Object>> batch = list.subList(i, end);
            futures.add(CompletableFuture.runAsync(() -> processBatch(batch), executor));
        }
        // 等待所有异步任务完成并处理异常
        CompletableFuture.allOf(futures.toArray(new CompletableFuture[0])).exceptionally(ex -> {
            // 更完善的异常处理，例如使用日志记录
            TOrderService.log.error("Error occurred during async task", ex);
            return null;
        }).join();
        return list;
    }

    private void processBatch(List<Map<String, Object>> batch) {
        List<Integer> orderIds = batch.stream().map(item -> ToolUtils.objToInteger(item.get("orderId"))).distinct().collect(Collectors.toList());
        Map<Integer, List<TOrderBill>> billsMap = tOrderBillMapper.listCustomerBillsByOrderIds(orderIds).stream().collect(Collectors.groupingBy(TOrderBill::getOrderId));

        for (Map<String, Object> item : batch) {
            Integer orderId = ToolUtils.objToInteger(item.get("orderId"));
            List<TOrderBill> bills = billsMap.getOrDefault(orderId, Collections.emptyList());
            setExportData(item, bills);
        }
    }

    public void setExportData(Map<String, Object> item, List<TOrderBill> bills) {
        if (ToolUtils.isListEmpty(bills)) {
            return;
        }
        TOrderBill bill1 = bills.get(0);
        item.put("rentFirst", bill1.getPayAmount());
        item.put("totalPayAmount", ToolUtils.formatDouble(bills.stream().mapToDouble(TOrderBill::getPayAmount).sum()));//总租金
        item.put("realPayAmount", ToolUtils.formatDouble(bills.stream().filter(ob -> ToolUtils.payStatusBuyout.contains(ob.getBillStatus())).mapToDouble(TOrderBill::getPayAmount).sum()));//已付租金

        LocalDateTime renewBegin = null;
        LocalDateTime renewEnd = null;
        List<Map> renews = new ArrayList<>();
        if (!item.get("renewNum").equals(0)) {//续租
            for (TOrderBill bill : bills) {
                if (bill.getRenewBill().equals(0)) {
                    continue;
                }
                Map<String, Object> renew = new HashMap<>();
                renew.put("beginTime", bill.getBeginTime());
                renew.put("endTime", bill.getEndTime());
                renew.put("payAmount", bill.getPayAmount());
                renews.add(renew);
            }
        }
        item.put("renews", renews);//续租账单
        TOrderBill bill = bills.stream().filter(ob -> ob.getNum().compareTo(0) >= 1 && ob.getBillStatus().equals(0)).findFirst().orElse(null);
        int outDay = 0;
        if (bill != null) {
            outDay = ToolUtils.getDaysBetween(bill.getEndTime(), LocalDateTime.now());
        }
        item.put("outDay", outDay);//逾期天数
    }

    /**
     * @Description 订单完结解冻押金
     * @Date 2024/9/30 13:11
     * @Author YWX
     * @Param [orderId]
     * @Return void
     **/
    @Transactional(rollbackFor = Exception.class)
    public void end(Integer orderId) {
        TOrder order = checkOrder(orderId);
        //已完结的不在处理
        if (order.getOrderStatus().equals(6)) {
            return;
        }
        serviceUtil.aliOrderEnd(order);
        TOrder order2 = new TOrder();
        order2.setOrderId(orderId);
        order2.setOrderStatus(6);
        tOrderMapper.updateById(order2);

        //添加操作日志
        TOrderLog log = new TOrderLog();
        log.setOrderCode(order.getOrderCode());
        log.setLogType("完结订单");
        log.setComm("商家" + "完结订单");
        orderLogService.saveOrderLog(log);

        AlipayCreate.deliveryModify(order.getOrderCode(), customerMapper.getOpenIdByCustomerId(order.getCustomerid()), "RETURNED");
    }

    /**
     * @Description 确认收货
     * @Date 2024/10/25 15:11
     * @Author YWX
     * @Param [orderId]
     * @Return void
     **/
    @Transactional(rollbackFor = Exception.class)
    public void confirmReceipt(String orderCode) {
        TOrder order = tOrderMapper.selectByOrderCode(orderCode);
        //已收货的不在处理
        if (order.getOrderStatus().compareTo(4) > 0) {
            return;
        }

        LocalDate beginDate = LocalDate.now();
        LocalDateTime beginTime = beginDate.plusDays(1).atTime(00, 00, 00);
        long seconds = Duration.between(order.getRealBegin(), beginTime).getSeconds();
        TOrder updateOrder = new TOrder();
        Integer orderId = order.getOrderId();
        updateOrder.setOrderId(orderId);
        updateOrder.setRealBegin(beginTime);
        LocalDateTime endtime = order.getRealEnd().plusSeconds(seconds);
        if (endtime.getSecond() != 59) {
            endtime = endtime.minusSeconds(1);
        }
        updateOrder.setRealEnd(endtime);
        updateOrder.setLeaseFixed(1);
        updateOrder.setOrderStatus(4);
        tOrderMapper.updateLeaseFixedById(updateOrder);
        tOrderBillMapper.updatePeriod2(orderId, seconds);

        //添加操作日志
        TOrderLog log = new TOrderLog();
        log.setOrderCode(order.getOrderCode());
        log.setLogType("确认收货");
        log.setComm("商家" + "确认收货");
        orderLogService.saveOrderLog(log);

        AlipayCreate.deliveryReceive(orderCode, customerMapper.getOpenIdByCustomerId(order.getCustomerid()));
    }

    /**
     * @Description 审核取消订单
     * @Date 2024/10/9 23:16
     * @Author YWX
     * @Param [order]
     * @Return void
     **/
    @Transactional(rollbackFor = Exception.class)
    public void checkCancel(TOrder order) {
        TOrder tOrder = tOrderMapper.selectByOrderCode(order.getOrderCode());
        if (tOrder == null) {
            throw new ServiceException("订单不存在！");
        } else if (ToolUtils.isTrueInteger(tOrder.getCancelCheckStatus())) {
            throw new ServiceException("您已经审核过取消订单，请勿重复操作！");
        }

        Integer cancelCheckStatus = order.getCancelCheckStatus();
        String result;
        Integer orderId = tOrder.getOrderId();
        if (cancelCheckStatus.equals(2)) {//同意
            serviceUtil.aliOrderCancle(tOrder);//支付宝订单取消
            order.setOrderStatus(7);
            if (tOrder.getOrderType().equals(1)) {
                List<TOrderBill> bills = tOrderBillMapper.listBuyOutBillByOrderPid(orderId);//获取订单的买断账单
                if (ToolUtils.isNotEmpty(bills)) {
                    serviceUtil.cancelBill(bills);
                }
                tOrderMapper.cancelBuyOutOrder(orderId);//取消买断订单
                //恢复库存
                goodsSpecsMapper.recoverStock(tOrder.getGsid(), tOrder.getNum());
            }
            result = "同意取消订单";
            order.setControlComm("审核取消订单");
        } else {//拒绝
            result = "拒绝取消订单";
        }
        order.setCancelStatus(0);
        order.setOrderId(orderId);
        order.setCancelCheckTime(LocalDateTime.now());
        order.setCancelCheckId(serviceUtil.getUserId());
        tOrderMapper.updateById(order);

        //添加操作日志
        TOrderLog log = new TOrderLog();
        log.setOrderCode(order.getOrderCode());
        log.setLogType("审核取消订单");
        String cancelComm = order.getCancelCheckComm();
        if (ToolUtils.isNotEmpty(cancelComm)) {
            cancelComm = "无";
        }
        String comm = "商家" + result + "，审核意见：" + cancelComm;
        log.setComm(comm);
        orderLogService.saveOrderLog(log);
    }

    /**
     * @Description 申请取消信息
     * @Date 2024/10/9 23:42
     * @Author YWX
     * @Param [orderCode]
     * @Return java.util.Map<java.lang.String, java.lang.Object>
     **/
    public Map<String, Object> detailCancel(String orderCode) {
        return tOrderMapper.detailCancel(orderCode);
    }

    /**
     * @Description 账单发起代扣
     * @Date 2024/10/22 22:28
     * @Author YWX
     * @Param [obid]
     * @Return void
     **/
    public void depositToPaymentByObid(Integer obid) {
        TOrderBill bill = tOrderBillMapper.selectById(obid);
        if (bill == null) {
            throw new ServiceException("账单不存在！");
        }
        Integer billStatus = bill.getBillStatus();
        if (billStatus.equals(1)) {
            throw new ServiceException("账单已支付！");
        }
        if (billStatus.equals(2)) {
            throw new ServiceException("账单已退款！");
        }
        if (billStatus.equals(3)) {
            throw new ServiceException("账单已关闭！");
        }
        TOrder tOrder = tOrderMapper.getRestAmountByOrderId(bill.getOrderId());//获取订单当前剩余冻结金额
        if (tOrder.getConfirmed().equals(0)) {
            throw new ServiceException("订单风控审核后才能发起代扣！");
        }
        Double restAmount = tOrder.getRestAmount();
        Double payAmount = bill.getPayAmount();
        if (payAmount.compareTo(restAmount) > 0) {//如果待支付金额大于冻结押金
            throw new ServiceException("待支付金额大于冻结押金！");
        }
        String orderCode = tOrder.getOrderCode();
        //发起分期单
        bill.setOrderCode(orderCode);
        String openid = customerMapper.getOpenIdByCustomerId(tOrder.getCustomerid());
        String type = ToolUtils.getTypeByOrderType(tOrder.getOrderType());
        String installmentOrderId = null;
        if (tOrder.getConfirmed().equals(1)) {
            AlipayOpenMiniOrderInstallmentCreateResponse createResponse = AlipayCreate.orderInstallmentCreate(bill, openid, type, false);
            installmentOrderId = createResponse.getInstallmentOrderId();
        }
        String body = "商家：" + serviceUtil.getStoreName(tOrder.getStoreid()) + "；订单号：" + tOrder.getOrderCode();
        updateBillStatus(obid, bill.getTransactionId(), tOrder.getAuthNo(), payAmount, bill.getOrderId(), installmentOrderId, tOrder.getTradeComponentOrderId(), body);//更新账单状态
        Integer firstPayStatus = null;
        if (bill.getPeriod().equals(1)) {
            firstPayStatus = 1;
        }
        updateRestAmountByCode(orderCode, restAmount, firstPayStatus);//更新订单剩余冻结金额
        //添加操作日志
        TOrderLog log = new TOrderLog();
        log.setOrderCode(tOrder.getOrderCode());
        String userName = serviceUtil.getUserName();
        log.setComm(userName + "冻结押金转支付第" + bill.getPeriod() + "期,支付金额：" + payAmount + "元");
        log.setLogType("冻结押金转支付");
        orderLogService.saveOrderLog(log);
    }

    //更新账单状态
    private void updateBillStatus(Integer obid, String transactionId, String authNo, Double payAmount, Integer orderId, String installmentOrderId, String tradeComponentOrderId
            , String body) {
        AlipayTradePayResponse response1 = AlipayCreate.alipayTradePay3(transactionId, authNo, "押金转支付", body, payAmount, installmentOrderId, tradeComponentOrderId, tOrderMapper.getGoodsDetail(orderId));
        TOrderBill bill1 = new TOrderBill();
        bill1.setObid(obid);
        if (response1.isSuccess() || response1.getSubMsg().equals("交易已经支付")) {
            Date gmtPayment = response1.getGmtPayment();//付款时间
            // 转换为LocalDateTime
            LocalDateTime localDateTime = ToolUtils.dateToLocalDateTime(gmtPayment);
            bill1.setRealDate(localDateTime.format(DateTimeFormatter.ofPattern("yyyy-MM-dd")));
            bill1.setPayTime(localDateTime);
            bill1.setCutTime(localDateTime);
            bill1.setTradeStatus(1);
            bill1.setBillStatus(1);
            bill1.setAvailableAmount(payAmount);
            bill1.setPayType(2);
            if (response1.isSuccess()) {
                serviceUtil.addAccountBillByTradeNo(transactionId, 1, 31);
            }
        }
        bill1.setInstallmentOrderId(installmentOrderId);
        tOrderBillMapper.updateByIdForService(bill1);//服务端扣款更新账单状态
    }

    //更新订单剩余冻结金额
    private void updateRestAmountByCode(String orderCode, Double restAmount, Integer firstPayStatus) {
        AlipayFundAuthOperationDetailQueryResponse response = AlipayCreate.alipayFundAuthOperationDetailQuery(orderCode);//资金授权操作查询
        if (response.isSuccess()) {
            String restAmount1 = response.getRestAmount();
            if (restAmount.compareTo(ToolUtils.objToDouble(restAmount1)) != 0) {
                TOrder order = new TOrder();
                order.setOrderCode(orderCode);
                order.setRestAmount(ToolUtils.objToDouble(restAmount1));
                order.setFirstPayStatus(firstPayStatus);
                tOrderMapper.updateRestAmountByCode(order);
            }
        }
    }

    /**
     * @Description 申请续租
     * @Date 2024/10/26 23:05
     * @Author YWX
     * @Param [entity]
     * @Return void
     **/
    @Transactional(rollbackFor = Exception.class)
    public void renewLease(OrderBillEntity entity) {
        String orderCode = entity.getOrderCode();
        TOrder tOrder = checkOrderByCode(orderCode);
        Integer orderStatus = tOrder.getOrderStatus();
        if (orderStatus.equals(6)) {
            throw new ServiceException("订单已完结，无法续租！");
        } else if (orderStatus.equals(7)) {
            throw new ServiceException("订单已取消，无法续租！");
        }
        TOrderBill bill = new TOrderBill();
        bill.setOrderId(tOrder.getOrderId());
        bill.setEndTime(ToolUtils.getEndDateTime(entity.getEndTime()));
        bill.setBillStatus(0);
        bill.setStoreid(tOrder.getStoreid());
        Double rent = entity.getRent();
        Double inRent = entity.getInRent();
        List<TOrderBill> bills;
        if (rent != null) {
            entity.setComm(entity.getComm() + " 总租金：" + rent + "元，输入总租金：" + inRent + "元");
        }
        if (rent != null && rent.compareTo(inRent) != 0) {
            bills = serviceUtil.setBillPrice2(bill, rent, inRent);
        } else {
            bills = serviceUtil.setBillPrice(bill, entity.getCouponid(), 1);
        }
        tOrderBillMapper.insertBatchSomeColumn(bills);

        //更新续租状态
        TOrder order = new TOrder();
        order.setOrderId(tOrder.getOrderId());
        order.setRenewStatus(1);
        order.setRealEnd(bills.get(bills.size() - 1).getEndTime());
        order.setLeasePeriod(tOrder.getLeasePeriod() + bills.size());
        order.setDay(ToolUtils.getDaysBetween(tOrder.getRealBegin(), bill.getEndTime()));
        tOrderMapper.updateRenewById(order);

        //记录日志
        TOrderLog orderLog = new TOrderLog();
        orderLog.setOrderCode(tOrder.getOrderCode());
        orderLog.setLogType("商家申请续租");
        orderLog.setComm(entity.getComm() + "；续租申请成功，续租金额：" + bill.getPayAmount());

        serviceUtil.orderModify(tOrder.getOrderId(), orderCode, tOrder.getCustomerid(), orderLog);
    }

    private @NotNull TOrder checkOrderByCode(String orderCode) {
        TOrder tOrder = tOrderMapper.selectByOrderCode(orderCode);
        if (tOrder == null) {
            throw new ServiceException("订单不存在！");
        }
        return tOrder;
    }

    /**
     * @Description 修改收货地址
     * @Date 2024/10/26 23:15
     * @Author YWX
     * @Param [orderCode, userAddress]
     * @Return void
     **/
    public void updateUserAddress(String orderCode, String userAddress, String username, String userphone) {
        TOrder order = checkOrderByCode(orderCode);
        TOrder order2 = new TOrder();
        order2.setOrderId(order.getOrderId());
        order2.setUserAddress(userAddress);
        if (ToolUtils.isNotEmpty(username)) {
            order2.setUsername(username);
        }
        if (ToolUtils.isNotEmpty(userphone)) {
            order2.setUserphone(userphone);
        }
        tOrderMapper.updateById(order2);
        TOrderLog log = new TOrderLog();
        log.setOrderCode(orderCode);
        log.setLogType("修改收货地址");
        log.setComm("收货地址：" + userAddress);
        orderLogService.saveOrderLog(log);
    }

    /**
     * @Description 获取订单状态数量
     * @Date 2024/10/27 10:54
     * @Author YWX
     * @Param [entity]
     * @Return java.util.Map
     **/
    public Map getStatusNum(OrderEntity entity) {
        return tOrderMapper.getStatusNum(entity);
    }

    /**
     * @Description 获取订单分配人
     * @Date 2024/10/27 16:58
     * @Author YWX
     * @Param [entity]
     * @Return java.util.List<java.util.Map>
     **/
    public List<Map> listManager(OrderEntity entity) {
        return tOrderMapper.listManager(entity);
    }

    /**
     * @Description 添加订单备注
     * @Date 2024/10/28 21:53
     * @Author YWX
     * @Param [comm]
     * @Return void
     **/
    public void addComm(TOrderComm comm) {
        TUser user = serviceUtil.getUser();
        comm.setCommType(user.getUsertype());
        orderCommMapper.insert(comm);

        TOrderLog log = new TOrderLog();
        log.setOrderCode(comm.getOrderCode());
        log.setLogType("添加订单备注");
        log.setComm(comm.getComm());
        orderLogService.saveOrderLog(log);
    }

    /**
     * @Description 订单备注列表
     * @Date 2024/10/28 21:56
     * @Author YWX
     * @Param [orderCode]
     * @Return java.util.List<java.util.Map < java.lang.String, java.lang.Object>>
     **/
    public List<Map<String, Object>> listOrderComm(String orderCode) {
        return orderCommMapper.listOrderComm(orderCode);
    }

    /**
     * @Description 获取可退款金额
     * @Date 2024/10/30 23:16
     * @Author YWX
     * @Param [orderCode]
     * @Return java.lang.Double
     **/
    public Double getRefundableAmount(String orderCode) {
        TOrder order = checkOrderByCode(orderCode);
        return tOrderBillMapper.getRefundableAmount(order.getOrderId());
    }

    /**
     * @Description 重新生成指定账单
     * @Date 2024/10/31 0:27
     * @Author YWX
     * @Param [obid]
     * @Return void
     **/
    public void reGenerateBill(Integer obid) {
        TOrderBill bill = tOrderBillMapper.findByObId(obid);
        if (bill == null) {
            throw new ServiceException("账单不存在！");
        } else if (bill.getNum().compareTo(0) > 0) {
            throw new ServiceException("该期账单已存在，禁止重新生成！");
        }
        Integer orderStatus = tOrderMapper.getOrderStatusById(bill.getOrderId());
        if (orderStatus.equals(6)) {
            throw new ServiceException("订单已完结，无法重新生成账单！");
        } else if (orderStatus.equals(7)) {
            throw new ServiceException("订单已取消，无法重新生成账单！");
        }
        bill.setObid(null);
        bill.setTransactionId(CodeUtil.generateBillSequence());
        bill.setIsGenerate(0);
        bill.setBillStatus(0);
        bill.setTradeStatus(0);
        bill.setTradeNo(null);
        bill.setPayType(0);
        bill.setRealDate(null);
        bill.setPayTime(null);
        bill.setCutTime(null);
        bill.setNum(0);
        tOrderBillMapper.insert(bill);
        TOrderLog log = new TOrderLog();
        log.setOrderCode(tOrderMapper.getCodeById(bill.getOrderId()));
        log.setLogType("重新生成账单");
        log.setComm("重新生成第" + bill.getPeriod() + "期账单");
        orderLogService.saveOrderLog(log);
    }

    /**
     * @Description 获取可退款账单列表
     * @Date 2024/11/1 22:24
     * @Author YWX
     * @Param [orderId]
     * @Return java.util.List<cn.psvmc.cxzapi.model.order.TOrderBill>
     **/
    public List<TOrderBill> listBillForRefund(Integer orderId) {
        return tOrderBillMapper.listBillForRefund(orderId);
    }

    /**
     * @Description 订单退款
     * @Date 2024/11/1 23:21
     * @Author YWX
     * @Param [log]
     * @Return void
     **/
    public void orderRefund(TOrderLog log) {
        String orderCode = log.getOrderCode();
        rwLock.readLock().lock();
        Double totalAmount;
        Double amount;
        List<Integer> obids;
        Integer obid;
        Integer orderId;
        Integer storeId;
        Map<Integer, TOrderBill> billMap;
        try {
            TOrder order = tOrderMapper.selectByOrderCode(orderCode);
            if (order == null) {
                throw new ServiceException("订单不存在！");
            }
            orderId = order.getOrderId();
            storeId = order.getStoreid();
            totalAmount = 0.0;
            amount = log.getAmount();
            obids = log.getObids();
            obid = log.getObid();
            if (ToolUtils.isListEmpty(obids) && !ToolUtils.isTrueInteger(obid)) {
                throw new ServiceException("请选择要退款的期数！");
            }
            List<TOrderBill> bills = tOrderBillMapper.listBillForRefund(orderId);
            billMap = new HashMap<>(bills.size());
            for (TOrderBill bill : bills) {
                bill.setOrderCode(orderCode);
                bill.setStoreid(order.getStoreid());
                billMap.put(bill.getObid(), bill);
            }
        } finally {
            rwLock.readLock().unlock();
        }
        rwLock.writeLock().lock();
        try {
            StringBuilder billComm = new StringBuilder();
            if (ToolUtils.isListNotEmpty(obids)) {
                for (Integer id : obids) {
                    TOrderBill bill = billMap.get(id);
                    if (bill == null) {
                        throw new ServiceException("账单没有可退款金额！");
                    }
                    Double availableAmount = bill.getAvailableAmount();
                    if (availableAmount.compareTo(0.0) <= 0) {
                        continue;
                    }
                    Double refundAmount;
                    billComm.append("第").append(bill.getPeriod()).append("期，");
                    if (availableAmount.compareTo(bill.getPayAmount()) < 0) {//部分退款
                        bill.setSendBackFee(availableAmount);
                        refundAmount = serviceUtil.orderBillRefund3(bill, 2);
                        billComm.append("部分退款");
                    } else {//全部退款
                        refundAmount = serviceUtil.orderBillRefund3(bill, 1);
                        billComm.append("全部退款");
                    }
                    totalAmount = ToolUtils.add(totalAmount, refundAmount);
                    billComm.append(",退款金额：").append(refundAmount).append("元\n");
                }
            }

            if (ToolUtils.isTrueInteger(obid)) {
                if (amount == null || amount.compareTo(0.0) <= 0) {
                    throw new ServiceException("部分退款金额不能为空！");
                }
                TOrderBill bill = billMap.get(obid);
                if (bill == null) {
                    throw new ServiceException("账单没有可退款金额！");
                }
                if (amount.compareTo(bill.getAvailableAmount()) > 0) {
                    throw new ServiceException("退款金额不能大于可退款金额！");
                }
                bill.setSendBackFee(amount);
                Double refundAmount = serviceUtil.orderBillRefund3(bill, 2);
                billComm.append("第").append(bill.getPeriod()).append("期，部分退款，退款金额：").append(refundAmount).append("元\n");
                totalAmount = ToolUtils.add(totalAmount, refundAmount);
            }

            if (totalAmount.compareTo(0.0) > 0) {
                serviceUtil.addAccountBillByOrderCode(orderCode, storeId, totalAmount, 2, orderId, billComm.toString());
            }

            String userName = serviceUtil.getUserName();
            log.setLogType("申请退款");
            String comm = log.getComm();
            String content = userName + "申请退款，退款金额：" + totalAmount + "元";
            if (ToolUtils.isNotEmpty(comm)) {
                content += "，原因：" + comm;
            }

            log.setComm(content);
        } catch (Exception e) {
            log.setComm("申请退款失败！原因：" + e.getMessage());
            throw new RuntimeException(e.getMessage());
        } finally {
            rwLock.writeLock().unlock();
            orderLogService.saveOrderLog(log);
        }
    }

    /**
     * @Description 获取续租实付金额
     * @Date 2024/11/7 22:09
     * @Author YWX
     * @Param [entity]
     * @Return java.lang.Object
     **/
    public Object getRenewLeasePrice(OrderBillEntity entity) {
        TOrder order = tOrderMapper.selectByOrderCode(entity.getOrderCode());
        if (order == null) {
            throw new ServiceException("订单不存在！");
        }
        TOrderBill bill = new TOrderBill();
        bill.setOrderId(order.getOrderId());
        bill.setEndTime(ToolUtils.getEndDateTime(entity.getEndTime()));
        serviceUtil.setBillPrice(bill, entity.getCouponid(), 0);
        return bill.getPayAmount();
    }

    /**
     * @Description 修改订单租期
     * @Date 2024/11/9 22:55
     * @Author YWX
     * @Param [entity]
     * @Return void
     **/
    @Transactional(rollbackFor = Exception.class)
    public void updateOrderPeriod(OrderBillEntity entity) {
        TOrder order = checkOrderByCode(entity.getOrderCode());
        if (order.getOrderStatus().equals(7)) {
            throw new ServiceException("订单已取消，禁止操作！");
        }
        int day = ToolUtils.getDaysBetween2(order.getRealBegin(), entity.getBegindate());
        Integer orderId = order.getOrderId();
        TOrder updateOrder = new TOrder();
        updateOrder.setOrderId(orderId);
        updateOrder.setRealBegin(order.getRealBegin().plusDays(day));
        updateOrder.setRealEnd(order.getRealEnd().plusDays(day));
        tOrderMapper.updateById(updateOrder);
        tOrderBillMapper.updatePeriod(orderId, day);

        TOrderLog log = new TOrderLog();
        log.setOrderCode(order.getOrderCode());
        log.setLogType("修改租期");
        log.setComm("起租日由：" + order.getRealBegin().format(DateTimeFormatter.ofPattern("yyyy-MM-dd")) + "，修改为：" + entity.getBegindate());
        String comm = entity.getComm();
        if (ToolUtils.isNotEmpty(comm)) {
            log.setComm(log.getComm() + "，备注：" + comm);
        }

        serviceUtil.orderModify(orderId, order.getOrderCode(), order.getCustomerid(), log);
    }

    /**
     * @Description 根据客户ID获取客户姓名和身份证号码
     * @Date 2024/11/16 22:25
     * @Author YWX
     * @Param [customerid]
     * @Return java.util.Map
     **/
    public Map getNameAndIdNumber(Integer customerid) {
        return customerMapper.getNameAndIdNumber(customerid);
    }

    /**
     * @Description 逾期订单导出列表
     * @Date 2024/12/17 22:53
     * @Author YWX
     * @Param [entity]
     * @Return java.util.List<java.util.Map < java.lang.String, java.lang.Object>>
     **/
    public List<Map<String, Object>> listExportExpected(OrderEntity entity) {
        setStoreId(entity);
        return tOrderMapper.listExpected(entity);
    }

    /**
     * @Description 新增订单申请记录
     * @Date 2024/12/18 22:22
     * @Author YWX
     * @Param [record]
     * @Return void
     **/
    public void addRecord(TOrderRecord record) {
        Integer rtype = record.getRtype();
        String orderCode = record.getOrderCode();
        ToolUtils.validation(new Object[]{orderCode, "订单号", 2, rtype, "类型", 1});
        TOrder order = tOrderMapper.selectByOrderCode(orderCode);
        if (order.getOrderStatus().equals(7)) {
            throw new ServiceException("订单已取消，禁止操作！");
        }
        record.setStoreid(order.getStoreid());
        //记录日志
        TOrderLog orderLog = new TOrderLog();
        orderLog.setOrderCode(orderCode);
        if (rtype.equals(1)) {//申请续租
            ToolUtils.validation(new Object[]{
                    record.getEndTime(), "结束日期", 1
            });
        } else if (rtype.equals(2)) {//申请退款
            ToolUtils.validation(new Object[]{
                    record.getAmount(), "金额", 2
            });
        } else if (rtype.equals(3)) {//修改账单金额
            ToolUtils.validation(new Object[]{
                    record.getPeriod(), "期数", 1
                    , record.getAmount(), "金额", 2
            });
        } else if (rtype.equals(4)) {//修改账单支付状态
            ToolUtils.validation(new Object[]{
                    record.getPeriod(), "期数", 1
                    , record.getBillStatus(), "账单状态", 2
            });
        } else if (rtype.equals(5)) {//更换账单期数
            ToolUtils.validation(new Object[]{
                    record.getPeriod(), "申请更换前的租期", 1
                    , record.getNewPeriod(), "申请更换后的期数", 1
            });
        }
        record.setStatus(0);
        tOrderRecordMapper.insert(record);
        orderLog.setLogType("商家申请" + getTypeName(rtype));
        orderLog.setComm(record.getComm());
        orderLogService.saveOrderLog(orderLog);
    }

    //获取类型名称
    private String getTypeName(Integer rtype) {
        String logType;
        if (rtype.equals(1)) {//申请续租
            logType = "续租";
        } else if (rtype.equals(2)) {//申请退款
            logType = "退款";
        } else if (rtype.equals(3)) {//修改账单金额
            logType = "修改账单金额";
        } else if (rtype.equals(4)) {//修改账单支付状态
            logType = "修改账单支付状态";
        } else if (rtype.equals(5)) {//更换账单期数
            logType = "更换账单期数";
        } else {
            logType = "冻结押金转支付";
        }
        return logType;
    }

    /**
     * @Description 审核订单申请记录
     * @Date 2024/12/18 22:32
     * @Author YWX
     * @Param [record]
     * @Return void
     **/
    @Transactional(rollbackFor = Exception.class)
    public void checkRecord(TOrderRecord record) {
        TOrderRecord orderRecord = tOrderRecordMapper.findById(record.getOrid());
        if (!orderRecord.getCheckStatus().equals(0)) {
            throw new ServiceException("该记录已审核，请勿重复操作！");
        }
        Integer rtype = orderRecord.getRtype();
        String orderCode = orderRecord.getOrderCode();
        String logComm = "";
        String comm = orderRecord.getComm();
        if (ToolUtils.isNotEmpty(comm)) {
            logComm = "申请原因：" + comm;
        }
        String checkComm = record.getCheckComm();
        if (ToolUtils.isNotEmpty(checkComm)) {
            if (ToolUtils.isNotEmpty(logComm)) {
                logComm += "  ";
            }
            logComm += "审核意见：" + checkComm;
        }
        Integer billStatus = orderRecord.getBillStatus();
        if (ToolUtils.isEmpty(checkComm)) {
            logComm = "申请原因：" + getTypeName(rtype);
            if (rtype.equals(1)) {
                logComm += "，续租结束日期：" + orderRecord.getEndTime();
            } else if (rtype.equals(2)) {
                logComm += "，退款金额：" + orderRecord.getTotalAmount();
            } else if (rtype.equals(3)) {
                logComm += "，期数：" + orderRecord.getPeriod() + "，金额：" + orderRecord.getAmount();
            } else if (rtype.equals(4)) {
                String status = billStatus.equals(1) ? "已支付" : "未支付";
                logComm += "，修改第" + orderRecord.getPeriod() + "期账单状态为：" + status;
            } else if (rtype.equals(5)) {
                logComm += "修改租期：第" + orderRecord.getPeriod() + "与第" + orderRecord.getNewPeriod() + "期金额互换";
            }
        }
        if (record.getCheckStatus().equals(1)) {
            if (rtype.equals(1)) {//申请续租
                OrderBillEntity bill = new OrderBillEntity();
                bill.setOrderCode(orderCode);
                bill.setEndTime(orderRecord.getEndTime());
                bill.setComm(logComm);
                bill.setRent(orderRecord.getAmount());
                bill.setInRent(orderRecord.getInAmount());
                renewLease(bill);
            } else if (rtype.equals(2)) {//申请退款
                ToolUtils.validation(new Object[]{orderRecord.getAmount(), "金额", 2});
                TOrderLog log = new TOrderLog();
                log.setOrderCode(orderCode);
                log.setAmount(orderRecord.getAmount());
                String obids = orderRecord.getObids();
                if (ToolUtils.isNotEmpty(obids)) {
                    String[] split = obids.split(",");
                    List<Integer> obids2 = new ArrayList<>();
                    for (String s : split) {
                        obids2.add(Integer.parseInt(s));
                    }
                    log.setObids(obids2);
                }
                log.setObid(orderRecord.getObid());
                log.setComm(logComm);
                orderRefund(log);
            } else if (rtype.equals(3)) {//修改账单金额
                TOrderBill bill = new TOrderBill();
                bill.setOrderCode(orderCode);
                bill.setPeriod(orderRecord.getPeriod());
                bill.setBillAmount(orderRecord.getAmount());
                bill.setComm(logComm);
                updateBillAmount(bill);
            } else if (rtype.equals(4)) {//修改账单支付状态
                TOrderBill bill = new TOrderBill();
                bill.setOrderCode(orderCode);
                bill.setPeriod(orderRecord.getPeriod());
                bill.setBillStatus(billStatus);
                bill.setComm(logComm);
                updateBillStatus(bill);
            } else if (rtype.equals(5)) {//更换账单期数
                TOrderBill bill = new TOrderBill();
                bill.setOrderCode(orderCode);
                bill.setPeriod(orderRecord.getPeriod());
                bill.setNewPeriod(orderRecord.getNewPeriod());
                bill.setComm(logComm);
                updatePeriod(bill);
            } else if (rtype.equals(6)) {//冻结押金转支付
                TOrder order = new TOrder();
                order.setOrderCode(orderCode);
                order.setStoreComm(logComm);
                convertDepositToPayment(order);
            }
        } else {
            TOrderLog log = new TOrderLog();
            log.setOrderCode(orderCode);
            log.setComm(checkComm);
            log.setLogType("商家申请" + getTypeName(rtype) + "未通过");
            orderLogService.saveOrderLog(log);
        }
        record.setStatus(record.getCheckStatus());
        record.setCheckId(serviceUtil.getUserId());
        record.setCheckTime(LocalDateTime.now());
        tOrderRecordMapper.updateById(record);
    }

    /**
     * @Description 订单申请记录列表
     * @Date 2024/12/19 21:33
     * @Author YWX
     * @Param [queryPage, entity]
     * @Return com.baomidou.mybatisplus.core.metadata.IPage<java.util.Map>
     **/
    public IPage<Map> listRecord(Page<TGoods> queryPage, OrderEntity entity) {
        return tOrderRecordMapper.listRecord(queryPage, entity);
    }

    /**
     * @Description 单个订单账单列表
     * @Date 2024/12/31 22:30
     * @Author YWX
     * @Param [orderCode]
     * @Return java.util.List<java.util.Map>
     **/
    public List<Map> listOrderBill(String orderCode) {
        return tOrderBillMapper.listOrderBill(orderCode);
    }

    /**
     * @Description 获取用户信息
     * @Date 2025/1/18 22:10
     * @Author YWX
     * @Param [orderCode]
     * @Return java.util.Map
     **/
    public Map getUserInfo(String orderCode) {
        return tOrderMapper.getUserInfo(orderCode);
    }

    /**
     * @Description 补充用户资料
     * @Date 2025/1/23 23:03
     * @Author YWX
     * @Param [auth]
     * @Return void
     **/
    public void updateUserProfile(TCustomerAuth auth) {
        Map<String, Object> map = customerAuthMapper.findByCustomerId(auth.getCustomerid());
        if (map != null && map.containsKey("caid")) {
            auth.setCaid(ToolUtils.objToInteger(map.get("caid")));
            customerAuthMapper.updateById(auth);
        } else {
            customerAuthMapper.insert(auth);
        }
    }
}
